#!/bin/bash

# Color
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 1. Define OLM address
OLM_ADDRESS="https://gitee.com/uccps-samples/uccps-operators/raw/master/olm/operator-lifecycle-manager/manifests/"  # Specify the address of OLM

# 2. Apply OLM manifests
echo -e "${BLUE}Installing OLM ...${NC}"
kubectl apply -f $OLM_ADDRESS/crd.yaml
kubectl apply -f $OLM_ADDRESS/olm.yaml
echo -e "${BLUE}Installing UCCPS Catalog ...${NC}"
kubectl apply -f $OLM_ADDRESS/catalog.yaml

# 3. Wait for OLM components to be ready
echo -e "${BLUE}Waiting for OLM components to be ready...${NC}"
kubectl rollout status deployment/olm-operator -n olm
kubectl rollout status deployment/catalog-operator -n olm
kubectl rollout status deployment/packageserver -n olm

echo -e "${BLUE}Waiting for UCCPS catalog to be ready...${NC}"
for ((i=1; i<=10; i++)); do
  catalog_pods=$(kubectl get pod -n uccps-operators -l olm.catalogSource=catalog --no-headers -o custom-columns=":metadata.name")
  pod_status=$(kubectl get pod $pod -n uccps-operators -o jsonpath='{.status.phase}')
  if [ "$pod_status" == "Running" ]; then
    echo "Pod $pod is running normally."
    break
  else
    #echo "Pod $pod is not running (current status: $pod_status). Attempt $i/$ATTEMPTS. Waiting for $WAIT_INTERVAL seconds..."
    sleep $WAIT_INTERVAL
  fi
done
if [ "$pod_status" != "Running" ]; then
  echo "Catalog Pod is still not running. Ignoring."
fi

# 4. Verify OLM installation
echo -e "${BLUE}Verifying OLM installation...${NC}"
olm_pods=$(kubectl get pods -n olm --no-headers -o custom-columns=":metadata.name")

if [ -z "$olm_pods" ]; then
  echo -e "${RED}OLM components not found. Installation may have failed.${NC}"
  exit 1
else
  echo -e "OLM components:"
  echo -e "$olm_pods"
fi

# 5. Check if all OLM pods are running
for pod in $olm_pods; do
  status=$(kubectl get pod $pod -n olm -o jsonpath='{.status.phase}')
  if [ "$status" != "Running" ]; then
    echo -e "${YELLOW}Pod $pod is not running (current status: $status).${NC}"
    exit 1
  fi
done

echo -e "${GREEN}OLM and UCCPS catalog has been successfully installed and all components are running.${NC}"